package com.dongliusuo.orangeforms.webadmin.app.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.alibaba.fastjson.JSONObject;
import com.dongliusuo.orangeforms.common.log.annotation.OperationLog;
import com.dongliusuo.orangeforms.common.log.model.constant.SysOperationLogType;
import com.github.pagehelper.page.PageMethod;
import com.dongliusuo.orangeforms.webadmin.app.vo.*;
import com.dongliusuo.orangeforms.webadmin.app.dto.*;
import com.dongliusuo.orangeforms.webadmin.app.model.*;
import com.dongliusuo.orangeforms.webadmin.app.service.*;
import com.dongliusuo.orangeforms.common.core.object.*;
import com.dongliusuo.orangeforms.common.core.util.*;
import com.dongliusuo.orangeforms.common.core.constant.*;
import com.dongliusuo.orangeforms.common.core.annotation.MyRequestBody;
import com.dongliusuo.orangeforms.webadmin.config.ApplicationConfig;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
 * 客户主数据操作控制器类。
 *
 * @author DongLiusuo
 * @date 2025-01-08
 */
@Tag(name = "客户主数据管理接口")
@Slf4j
@RestController
@RequestMapping("/admin/app/customerInfo")
public class CustomerInfoController {

    @Autowired
    private ApplicationConfig appConfig;
    @Autowired
    private CustomerInfoService customerInfoService;

    /**
     * 新增客户主数据数据，及其关联的从表数据。
     *
     * @param customerInfoDto 新增主表对象。
     * @param customerAccountDtoList 一对多客户银行卡数据从表列表。
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @ApiOperationSupport(ignoreParameters = {
            "customerInfoDto.customerId",
            "customerInfoDto.searchString",
            "customerInfoDto.birthDateStart",
            "customerInfoDto.birthDateEnd",
            "customerInfoDto.registrationDateStart",
            "customerInfoDto.registrationDateEnd"})
    @SaCheckPermission("customerInfo.add")
    @OperationLog(type = SysOperationLogType.ADD)
    @PostMapping("/add")
    public ResponseResult<Long> add(
            @MyRequestBody CustomerInfoDto customerInfoDto,
            @MyRequestBody List<CustomerAccountDto> customerAccountDtoList) {
        ResponseResult<Tuple2<CustomerInfo, JSONObject>> verifyResult =
                this.doBusinessDataVerifyAndConvert(customerInfoDto, false, customerAccountDtoList);
        if (!verifyResult.isSuccess()) {
            return ResponseResult.errorFrom(verifyResult);
        }
        Tuple2<CustomerInfo, JSONObject> bizData = verifyResult.getData();
        CustomerInfo customerInfo = bizData.getFirst();
        customerInfo = customerInfoService.saveNewWithRelation(customerInfo, bizData.getSecond());
        return ResponseResult.success(customerInfo.getCustomerId());
    }

    /**
     * 修改客户主数据数据，及其关联的从表数据。
     *
     * @param customerInfoDto 修改后的对象。
     * @param customerAccountDtoList 一对多客户银行卡数据从表列表。
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @ApiOperationSupport(ignoreParameters = {
            "customerInfoDto.customerId",
            "customerInfoDto.searchString",
            "customerInfoDto.birthDateStart",
            "customerInfoDto.birthDateEnd",
            "customerInfoDto.registrationDateStart",
            "customerInfoDto.registrationDateEnd"})
    @SaCheckPermission("customerInfo.update")
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/update")
    public ResponseResult<Long> update(
            @MyRequestBody CustomerInfoDto customerInfoDto,
            @MyRequestBody List<CustomerAccountDto> customerAccountDtoList) {
        String errorMessage;
        ResponseResult<Tuple2<CustomerInfo, JSONObject>> verifyResult =
                this.doBusinessDataVerifyAndConvert(customerInfoDto, true, customerAccountDtoList);
        if (!verifyResult.isSuccess()) {
            return ResponseResult.errorFrom(verifyResult);
        }
        Tuple2<CustomerInfo, JSONObject> bizData = verifyResult.getData();
        CustomerInfo originalCustomerInfo = bizData.getSecond().getObject("originalData", CustomerInfo.class);
        CustomerInfo customerInfo = bizData.getFirst();
        if (!customerInfoService.updateWithRelation(customerInfo, originalCustomerInfo, bizData.getSecond())) {
            errorMessage = "数据验证失败，[CustomerInfo] 数据不存在!";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        return ResponseResult.success(customerInfo.getCustomerId());
    }

    /**
     * 删除客户主数据数据。
     *
     * @param customerId 删除对象主键Id。
     * @return 应答结果对象。
     */
    @SaCheckPermission("customerInfo.delete")
    @OperationLog(type = SysOperationLogType.DELETE)
    @PostMapping("/delete")
    public ResponseResult<Void> delete(@MyRequestBody Long customerId) {
        if (MyCommonUtil.existBlankArgument(customerId)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        return this.doDelete(customerId);
    }

    /**
     * 批量删除客户主数据数据。
     *
     * @param customerIdList 待删除对象的主键Id列表。
     * @return 应答结果对象。
     */
    @SaCheckPermission("customerInfo.delete")
    @OperationLog(type = SysOperationLogType.DELETE_BATCH)
    @PostMapping("/deleteBatch")
    public ResponseResult<Void> deleteBatch(@MyRequestBody List<Long> customerIdList) {
        if (MyCommonUtil.existBlankArgument(customerIdList)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        for (Long customerId : customerIdList) {
            ResponseResult<Void> responseResult = this.doDelete(customerId);
            if (!responseResult.isSuccess()) {
                return responseResult;
            }
        }
        return ResponseResult.success();
    }

    /**
     * 列出符合过滤条件的客户主数据列表。
     *
     * @param customerInfoDtoFilter 过滤对象。
     * @param customerAccountDtoFilter 一对多从表过滤对象。
     * @param orderParam 排序参数。
     * @param pageParam 分页参数。
     * @return 应答结果对象，包含查询结果集。
     */
    @SaCheckPermission("customerInfo.view")
    @PostMapping("/list")
    public ResponseResult<MyPageData<CustomerInfoVo>> list(
            @MyRequestBody CustomerInfoDto customerInfoDtoFilter,
            @MyRequestBody CustomerAccountDto customerAccountDtoFilter,
            @MyRequestBody MyOrderParam orderParam,
            @MyRequestBody MyPageParam pageParam) {
        if (pageParam != null) {
            PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize(), pageParam.getCount());
        }
        CustomerInfo customerInfoFilter = MyModelUtil.copyTo(customerInfoDtoFilter, CustomerInfo.class);
        CustomerAccount customerAccountFilter = MyModelUtil.copyTo(customerAccountDtoFilter, CustomerAccount.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam, CustomerInfo.class);
        List<CustomerInfo> customerInfoList =
                customerInfoService.getCustomerInfoListWithRelation(customerInfoFilter, customerAccountFilter, orderBy);
        return ResponseResult.success(MyPageUtil.makeResponseData(customerInfoList, CustomerInfoVo.class));
    }

    /**
     * 导入主表数据列表。
     *
     * @param importFile 上传的文件，目前仅仅支持xlsx和xls两种格式。
     * @return 应答结果对象。
     */
    @SaCheckPermission("customerInfo.import")
    @OperationLog(type = SysOperationLogType.IMPORT)
    @PostMapping("/import")
    public ResponseResult<Void> importBatch(
            @RequestParam Boolean skipHeader,
            @RequestParam("importFile") MultipartFile importFile) throws IOException {
        String filename = ImportUtil.saveImportFile(appConfig.getUploadFileBaseDir(), null, importFile);
        // 这里可以指定需要忽略导入的字段集合。如创建时间、创建人、更新时间、更新人、主键Id和逻辑删除，
        // 以及一些存在缺省值且无需导入的字段。其中主键字段和逻辑删除字段不需要在这里设置，批量插入逻辑会自动处理的。
        Set<String> ignoreFieldSet = new HashSet<>();
        ignoreFieldSet.add("createdBy");
        ignoreFieldSet.add("createdTime");
        ignoreFieldSet.add("updatedBy");
        ignoreFieldSet.add("updatedTime");
        List<ImportUtil.ImportHeaderInfo> headerInfoList = ImportUtil.makeHeaderInfoList(CustomerInfo.class, ignoreFieldSet);
        // 下面是导入时需要注意的地方，如果我们缺省生成的代码，与实际情况存在差异，请手动修改。
        // 1. 头信息数据字段，我们只是根据当前的主表实体对象生成了缺省数组，开发者可根据实际情况，对headerInfoList进行修改。
        ImportUtil.ImportHeaderInfo[] headerInfos = headerInfoList.toArray(new ImportUtil.ImportHeaderInfo[]{});
        // 2. 这里需要根据实际情况决定，导入文件中第一行是否为中文头信息，如果是可以跳过。这里我们默认为true。
        // 这里根据自己的实际需求，为doImport的最后一个参数，传递需要进行字典转换的字段集合。
        // 注意，集合中包含需要翻译的Java字段名，如: gradeId。
        Set<String> translatedDictFieldSet = new HashSet<>();
        List<CustomerInfo> dataList =
                ImportUtil.doImport(headerInfos, skipHeader, filename, CustomerInfo.class, translatedDictFieldSet);
        CallResult result = customerInfoService.verifyImportList(dataList, translatedDictFieldSet);
        if (!result.isSuccess()) {
            // result中返回了具体的验证失败对象，如果需要返回更加详细的错误，可根据实际情况手动修改。
            return ResponseResult.errorFrom(result);
        }
        customerInfoService.saveNewBatch(dataList, -1);
        return ResponseResult.success();
    }

    /**
     * 导出符合过滤条件的客户主数据列表。
     *
     * @param customerInfoDtoFilter 过滤对象。
     * @param customerAccountDtoFilter 一对多从表过滤对象。
     * @param orderParam 排序参数。
     * @throws IOException 文件读写失败。
     */
    @SaCheckPermission("customerInfo.export")
    @OperationLog(type = SysOperationLogType.EXPORT, saveResponse = false)
    @PostMapping("/export")
    public void export(
            @MyRequestBody CustomerInfoDto customerInfoDtoFilter,
            @MyRequestBody CustomerAccountDto customerAccountDtoFilter,
            @MyRequestBody MyOrderParam orderParam) throws IOException {
        CustomerInfo customerInfoFilter = MyModelUtil.copyTo(customerInfoDtoFilter, CustomerInfo.class);
        CustomerAccount customerAccountFilter = MyModelUtil.copyTo(customerAccountDtoFilter, CustomerAccount.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam, CustomerInfo.class);
        List<CustomerInfo> resultList =
                customerInfoService.getCustomerInfoListWithRelation(customerInfoFilter, customerAccountFilter, orderBy);
        // 导出文件的标题数组
        // NOTE: 下面的代码中仅仅导出了主表数据，主表聚合计算数据和主表关联字典的数据。
        // 一对一从表数据的导出，可根据需要自行添加。如：headerMap.put("slaveFieldName.xxxField", "标题名称")
        Map<String, String> headerMap = new LinkedHashMap<>(30);
        headerMap.put("customerId", "唯一标识符");
        headerMap.put("firstName", "名");
        headerMap.put("lastName", "姓");
        headerMap.put("email", "电子邮件");
        headerMap.put("phoneNumber", "电话号码");
        headerMap.put("genderDictMap.name", "性别");
        headerMap.put("birthDate", "出生日期");
        headerMap.put("idTypeDictMap.name", "证件类型");
        headerMap.put("idNumber", "证件号码");
        headerMap.put("nationalityDictMap.name", "国籍");
        headerMap.put("provinceCodeDictMap.name", "省行政区划代码");
        headerMap.put("cityCodeDictMap.name", "市行政区划代码");
        headerMap.put("districtCodeDictMap.name", "区行政区划代码");
        headerMap.put("detailedAddress1", "详细地址1");
        headerMap.put("detailedAddress2", "详细地址2");
        headerMap.put("fullAddress", "完整地址");
        headerMap.put("occupation", "职业");
        headerMap.put("companyName", "公司名称");
        headerMap.put("incomeRangeDictMap.name", "收入范围");
        headerMap.put("emergencyContactName", "紧急联系人姓名");
        headerMap.put("emergencyContactPhone", "紧急联系人电话");
        headerMap.put("registrationDate", "注册日期");
        headerMap.put("lastLogin", "最后登录时间");
        headerMap.put("status", "用户状态");
        headerMap.put("remark", "其他备注信息");
        headerMap.put("createdBy", "创建人");
        headerMap.put("createdTime", "创建时间");
        headerMap.put("updatedBy", "更新人");
        headerMap.put("updatedTime", "更新时间");
        headerMap.put("deletedFlag", "删除标志");
        ExportUtil.doExport(resultList, headerMap, "customerInfo.xlsx");
    }

    /**
     * 查看指定客户主数据对象详情。
     *
     * @param customerId 指定对象主键Id。
     * @return 应答结果对象，包含对象详情。
     */
    @SaCheckPermission("customerInfo.view")
    @GetMapping("/view")
    public ResponseResult<CustomerInfoVo> view(@RequestParam Long customerId) {
        CustomerInfo customerInfo = customerInfoService.getByIdWithRelation(customerId, MyRelationParam.full());
        if (customerInfo == null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        CustomerInfoVo customerInfoVo = MyModelUtil.copyTo(customerInfo, CustomerInfoVo.class);
        return ResponseResult.success(customerInfoVo);
    }

    private ResponseResult<Tuple2<CustomerInfo, JSONObject>> doBusinessDataVerifyAndConvert(
            CustomerInfoDto customerInfoDto,
            boolean forUpdate,
            List<CustomerAccountDto> customerAccountDtoList) {
        ErrorCodeEnum errorCode = ErrorCodeEnum.DATA_VALIDATED_FAILED;
        String errorMessage = MyCommonUtil.getModelValidationError(customerInfoDto, false);
        if (errorMessage != null) {
            return ResponseResult.error(errorCode, errorMessage);
        }
        errorMessage = MyCommonUtil.getModelValidationError(customerAccountDtoList);
        if (errorMessage != null) {
            return ResponseResult.error(errorCode, "参数 [customerAccountDtoList] " + errorMessage);
        }
        // 全部关联从表数据的验证和转换
        JSONObject relationData = new JSONObject();
        CallResult verifyResult;
        // 下面是输入参数中，主表关联数据的验证。
        CustomerInfo customerInfo = MyModelUtil.copyTo(customerInfoDto, CustomerInfo.class);
        CustomerInfo originalData = null;
        if (forUpdate && customerInfo != null) {
            originalData = customerInfoService.getById(customerInfo.getCustomerId());
            if (originalData == null) {
                return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
            }
            relationData.put("originalData", originalData);
        }
        verifyResult = customerInfoService.verifyRelatedData(customerInfo, originalData);
        if (!verifyResult.isSuccess()) {
            return ResponseResult.errorFrom(verifyResult);
        }
        verifyResult = customerInfoService.verifyUniqueFieldValue(customerInfo, originalData);
        if (!verifyResult.isSuccess()) {
            return ResponseResult.errorFrom(verifyResult);
        }
        // 处理主表的一对多关联 [CustomerAccount]
        List<CustomerAccount> customerAccountList =
                MyModelUtil.copyCollectionTo(customerAccountDtoList, CustomerAccount.class);
        relationData.put("customerAccountList", customerAccountList);
        return ResponseResult.success(new Tuple2<>(customerInfo, relationData));
    }

    private ResponseResult<Void> doDelete(Long customerId) {
        String errorMessage;
        // 验证关联Id的数据合法性
        CustomerInfo originalCustomerInfo = customerInfoService.getById(customerId);
        if (originalCustomerInfo == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [对象] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        if (!customerInfoService.remove(customerId)) {
            errorMessage = "数据操作失败，删除的对象不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        return ResponseResult.success();
    }
}
